package com.netty.util;

import com.alibaba.fastjson.JSONArray;
import com.netty.constant.Constants;
import com.netty.model.MessageWrapper;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class DwrUtil {
    /**
     * 发送给全部
     */
    public static void sedMessageToAll(MessageWrapper msgModel) {

        try {
            Map<String, Object> map = new HashMap<>();
            map.put("user", msgModel.getSessionId());
            map.put("content", msgModel.getBody());
            final Object msg = JSONArray.toJSON(map);
            Browser.withAllSessions(new Runnable() {
                private ScriptBuffer script = new ScriptBuffer();

                @Override
                public void run() {
                    script.appendCall(Constants.DWRConfig.DWR_SCRIPT_FUNCTIONNAME, msg);
                    Collection<ScriptSession> sessions = Browser.getTargetSessions();
                    for (ScriptSession scriptSession : sessions) {
                        scriptSession.addScript(script);
                    }
                }
            });
        } catch (Exception ignored) {
        }
    }

    /**
     * 发送给个人
     */
    public static void sendMessageToUser(String userid, String message) {
        final String msg = message;
        final String attributeName = Constants.SessionConfig.SESSION_KEY;
        Browser.withAllSessionsFiltered(session -> {
            if (session.getAttribute(attributeName) == null) {
                return false;
            } else {
                return session.getAttribute(attributeName).equals(userid);
            }
        }, new Runnable() {
            private ScriptBuffer script = new ScriptBuffer();

            @Override
            public void run() {
                script.appendCall(Constants.DWRConfig.DWR_SCRIPT_FUNCTIONNAME, msg);
                Collection<ScriptSession> sessions = Browser.getTargetSessions();
                for (ScriptSession scriptSession : sessions) {
                    scriptSession.addScript(script);
                }
            }
        });
    }
}